{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Only execute if you haven't already. Make sure to restart the kernel if these libraries have not been previously installed.\n",
    "!pip install xgboost==0.82 --user\n",
    "!pip install scikit-learn==0.20.4 --user"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note**: You may need to restart the kernel to use updated packages."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Import Python packages\n",
    "\n",
    "Execute the command below (__Shift + Enter__) to load all the python libraries we'll need for the lab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime\n",
    "import pickle\n",
    "import os\n",
    "\n",
    "import pandas as pd\n",
    "import xgboost as xgb\n",
    "import numpy as np\n",
    "\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.pipeline import FeatureUnion, make_pipeline\n",
    "from sklearn.utils import shuffle\n",
    "from sklearn.base import clone\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "from witwidget.notebook.visualization import WitWidget, WitConfigBuilder\n",
    "\n",
    "import custom_transforms\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings(action='ignore', category=DeprecationWarning)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before we continue, note that we'll be using your Google Skills project id a lot in this notebook. For convenience, set it as an environment variable using the command below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ['QWIKLABS_PROJECT_ID'] = ''"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Download and process data\n",
    "\n",
    "The models you'll build will predict the income level, whether it's less than or equal to $50,000 per year, of individuals given 14 data points about each individual. You'll train your models on this UCI [Census Income Dataset](https://archive.ics.uci.edu/ml/datasets/Adult).\n",
    "\n",
    "We'll read the data into a Pandas DataFrame to see what we'll be working with. It's important to shuffle our data in case the original dataset is ordered in a specific way. We use an sklearn utility called shuffle to do this, which we imported in the first cell:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_csv_path = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'\n",
    "\n",
    "COLUMNS = (\n",
    "    'age',\n",
    "    'workclass',\n",
    "    'fnlwgt',\n",
    "    'education',\n",
    "    'education-num',\n",
    "    'marital-status',\n",
    "    'occupation',\n",
    "    'relationship',\n",
    "    'race',\n",
    "    'sex',\n",
    "    'capital-gain',\n",
    "    'capital-loss',\n",
    "    'hours-per-week',\n",
    "    'native-country',\n",
    "    'income-level'\n",
    ")\n",
    "\n",
    "raw_train_data = pd.read_csv(train_csv_path, names=COLUMNS, skipinitialspace=True)\n",
    "raw_train_data = shuffle(raw_train_data, random_state=4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`data.head()` lets us preview the first five rows of our dataset in Pandas."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_train_data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `income-level` column is the thing our model will predict. This is the binary outcome of whether the individual makes more than $50,000 per year. To see the distribution of income levels in the dataset, run the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(raw_train_data['income-level'].value_counts(normalize=True))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As explained in [this paper](http://cseweb.ucsd.edu/classes/sp15/cse190-c/reports/sp15/048.pdf), each entry in the dataset contains the following information\n",
    "about an individual:\n",
    "\n",
    "* __age__: the age of an individual\n",
    "* __workclass__: a general term to represent the employment status of an individual\n",
    "* __fnlwgt__: final weight. In other words, this is the number of people the census believes\n",
    "the entry represents...\n",
    "* __education__: the highest level of education achieved by an individual.\n",
    "* __education-num__: the highest level of education achieved in numerical form.\n",
    "* __marital-status__: marital status of an individual. \n",
    "* __occupation__: the general type of occupation of an individual\n",
    "* __relationship__: represents what this individual is relative to others. For example an\n",
    "individual could be a Husband. Each entry only has one relationship attribute and is\n",
    "somewhat redundant with marital status. \n",
    "* __race__: Descriptions of an individual’s race\n",
    "* __sex__: the biological sex of the individual\n",
    "* __capital-gain__: capital gains for an individual\n",
    "* __capital-loss__: capital loss for an individual\n",
    "* __hours-per-week__: the hours an individual has reported to work per week\n",
    "* __native-country__: country of origin for an individual\n",
    "* __income-level__: whether or not an individual makes more than $50,000 annually"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An important concept in machine learning is train / test split. We'll take the majority of our data and use it to train our model, and we'll set aside the rest for testing our model on data it's never seen before. There are many ways to create training and test datasets. Fortunately, for our census data we can simply download a pre-defined test set. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_csv_path = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test'\n",
    "raw_test_data = pd.read_csv(test_csv_path, names=COLUMNS, skipinitialspace=True, skiprows=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_test_data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since we don't want to train a model on our labels, we're going to separate them from the features in both the training and test datasets. Also, notice that `income-level` is a string datatype. For machine learning, it's better to convert this to an binary integer datatype. We do this in the next cell.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_train_features = raw_train_data.drop('income-level', axis=1).values\n",
    "raw_test_features = raw_test_data.drop('income-level', axis=1).values\n",
    "\n",
    "# Create training labels list\n",
    "train_labels = (raw_train_data['income-level'] == '>50K').values.astype(int)\n",
    "test_labels = (raw_test_data['income-level'] == '>50K.').values.astype(int)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now you're ready to build and train your first model!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Build a First Model\n",
    "\n",
    "The model we build closely follows a template for the [census dataset found on AI Hub](https://aihub.cloud.google.com/p/products%2F526771c4-9b36-4022-b9c9-63629e9e3289). For our model we use an XGBoost classifier. However, before we train our model we have to pre-process the data a little bit. We build a processing pipeline using [Scikit-Learn's Pipeline constructor](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html). We apply some custom transformations that are defined in `custom_transforms.py`. Open the file `custom_transforms.py` and inspect the code. Our features are either numerical or categorical. The numerical features are `age-num`, and `hours-per-week`. These features will be processed by applying [Scikit-Learn's StandardScaler function](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html). The categorical features are `workclass`, `education`, `marital-status`, and `relationship`. These features are [one-hot encoded](https://machinelearningmastery.com/why-one-hot-encode-data-in-machine-learning/). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numerical_indices = [0, 12]  \n",
    "categorical_indices = [1, 3, 5, 7]  \n",
    "\n",
    "p1 = make_pipeline(\n",
    "    custom_transforms.PositionalSelector(categorical_indices),\n",
    "    custom_transforms.StripString(),\n",
    "    custom_transforms.SimpleOneHotEncoder()\n",
    ")\n",
    "p2 = make_pipeline(\n",
    "    custom_transforms.PositionalSelector(numerical_indices),\n",
    "    StandardScaler()\n",
    ")\n",
    "p3 = FeatureUnion([\n",
    "    ('numericals', p1),\n",
    "    ('categoricals', p2),\n",
    "])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To finalize the pipeline we attach an XGBoost classifier at the end. The complete pipeline object takes the raw data we loaded from csv files, processes the categorical features, processes the numerical features, concatenates the two, and then passes the result through the XGBoost classifier.   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipeline = make_pipeline(\n",
    "    p3,\n",
    "    xgb.sklearn.XGBClassifier(max_depth=4)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We train our model with one function call using the fit() method. We pass the fit() method our training data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipeline.fit(raw_train_features, train_labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's go ahead and save our model as a pickle file. Executing the command below will save the trained model in the file `model.pkl` in the same directory as this notebook. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('model.pkl', 'wb') as model_file:\n",
    "    pickle.dump(pipeline, model_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Save Trained Model to AI Platform\n",
    "\n",
    "We've got our model working locally, but it would be nice if we could make predictions on it from anywhere (not just this notebook!). In this step we'll deploy it to the cloud. For detailed instructions on how to do this visit [the official documenation](https://cloud.google.com/ai-platform/prediction/docs/exporting-for-prediction). Note that since we have custom components in our data pipeline we need to go through a few extra steps.  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a Cloud Storage bucket for the model\n",
    "\n",
    "We first need to create a storage bucket to store our pickled model file. We'll point Cloud AI Platform at this file when we deploy. Run this gsutil command to create a bucket. This will ensure the name of the cloud storage bucket you create will be globally unique."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!gsutil mb gs://$QWIKLABS_PROJECT_ID"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Package custom transform code\n",
    "\n",
    "Since we're using custom transformation code we need to package it up and direct AI Platform to it when we ask it make predictions. To package our custom code we create a source distribution. The following code creates this distribution and then ports the distribution and the model file to the bucket we created. Ignore the warnings about missing meta data. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "\n",
    "python setup.py sdist --formats=gztar\n",
    "\n",
    "gsutil cp model.pkl gs://$QWIKLABS_PROJECT_ID/original/\n",
    "gsutil cp dist/custom_transforms-0.1.tar.gz gs://$QWIKLABS_PROJECT_ID/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create and Deploy Model\n",
    "\n",
    "The following ai-platform gcloud command will create a new model in your project. We'll call this one `census_income_classifier`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!gcloud ai-platform models create census_income_classifier --regions us-central1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now it's time to deploy the model. We can do that with this gcloud command:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "\n",
    "MODEL_NAME=\"census_income_classifier\"\n",
    "VERSION_NAME=\"original\"\n",
    "MODEL_DIR=\"gs://$QWIKLABS_PROJECT_ID/original/\"\n",
    "CUSTOM_CODE_PATH=\"gs://$QWIKLABS_PROJECT_ID/custom_transforms-0.1.tar.gz\"\n",
    "\n",
    "gcloud beta ai-platform versions create $VERSION_NAME \\\n",
    "  --model $MODEL_NAME \\\n",
    "  --runtime-version 1.15 \\\n",
    "  --python-version 3.7 \\\n",
    "  --origin $MODEL_DIR \\\n",
    "  --package-uris $CUSTOM_CODE_PATH \\\n",
    "  --prediction-class predictor.MyPredictor \\\n",
    "  --region=global"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While this is running, check the [models section](https://console.cloud.google.com/ai-platform/models) of your AI Platform console. You should see your new version deploying there. When the deploy completes successfully you'll see a green check mark where the loading spinner is. The deploy should take 2-3 minutes. You will need to click on the model name in order to see the spinner/checkmark. In the command above, notice we specify `prediction-class`. The reason we must specify a prediction class is that by default, AI Platform prediction will call a Scikit-Learn model's `predict` method, which in this case returns either 0 or 1. However, the What-If Tool requires output from a model in line with a Scikit-Learn model's `predict_proba` method.  This is because WIT wants the probabilities of the negative and positive classes, not just the final determination on which class a person belongs to. Because that allows us to do more fine-grained exploration of the model. Consequently, we must write a [custom prediction routine](https://cloud.google.com/ai-platform/prediction/docs/custom-prediction-routines) that basically renames `predict_proba` as `predict`. The custom prediction method can be found in the file `predictor.py`. This file was packaged in the section __Package custom transform code__. By specifying `prediction-class` we're telling AI Platform to call our custom prediction method--basically, `predict_proba`-- instead of the default `predict` method."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test the deployed model\n",
    "\n",
    "To make sure your deployed model is working, test it out using gcloud to make a prediction. First, save a JSON file with one test instance for prediction:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile predictions.json\n",
    "[25, \"Private\", 226802, \"11th\", 7, \"Never-married\", \"Machine-op-inspct\", \"Own-child\", \"Black\", \"Male\", 0, 0, 40, \"United-States\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Test your model by running this code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!gcloud ai-platform predict --model=census_income_classifier --json-instances=predictions.json --version=original --region=global"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should see your model's prediction in the output. The first entry in the output is the model's probability that the individual makes under \\\\$50K while the second entry is the model's confidence that the individual makes over \\\\$50k. The two entries sum to 1. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# What-If Tool"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To connect the What-if Tool to your AI Platform models, you need to pass it a subset of your test examples along with the ground truth values for those examples. Let's create a Numpy array of 2000 of our test examples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_datapoints = 2000  \n",
    "\n",
    "test_examples = np.hstack(\n",
    "    (raw_test_features[:num_datapoints], \n",
    "     test_labels[:num_datapoints].reshape(-1,1)\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Instantiating the What-if Tool is as simple as creating a WitConfigBuilder object and passing it the AI Platform model we built. Note that it'll take a minute to load the visualization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config_builder = (\n",
    "    WitConfigBuilder(test_examples.tolist(), COLUMNS)\n",
    "    .set_ai_platform_model(os.environ['QWIKLABS_PROJECT_ID'], 'census_income_classifier', 'original')\n",
    "    .set_target_feature('income-level')\n",
    "    .set_model_type('classification')\n",
    "    .set_label_vocab(['Under 50K', 'Over 50K'])\n",
    ")\n",
    "\n",
    "WitWidget(config_builder, height=800)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The default view on the What-if Tool is the __Datapoint editor__ tab. Here, you can click on any individual data point to see its features and even change feature values. Navigate to the __Performance & Fairness__ tab in the What-if Tool. By slicing on a feature you can view the model error for individual feature values. Finally, navigate to the __Features__ tab in the What-if Tool. This shows you the distribution of values for each feature in your dataset. You can use this tab to make sure your dataset is balanced. For example, if we only had Asians in a population, the model's predictions wouldn't necessarily reflect real world data. This tab gives us a good opportunity to see where our dataset might fall short, so that we can go back and collect more data to make it balanced.\n",
    "\n",
    "In the __Features__ tab, we can look to see the distribution of values for each feature in the dataset. We can see that of the 2000 test datapoints, 1346 are from men and 1702 are from caucasions. Women and minorities seem under-represented in this dataset. That may lead to the model not learning an accurate representation of the world in which it is trying to make predictions (of course, even if it does learn an accurate representation, is that what we want the model to perpetuate? This is a much deeper question still falling under the ML fairness umbrella and worthy of discussion outside of WIT). Predictions on those under-represented groups are more likely to be inaccurate than predictions on the over-represented groups.\n",
    "\n",
    "The features in this visualization can be sorted by a number of different metrics, including non-uniformity. With this sorting, the features that have the most non-uniform distributions are shown first. For numeric features, capital gain is very non-uniform, with most datapoints having it set to 0, but a small number having non-zero capital gains, all the way up to a maximum of 100k. For categorical features, country is the most non-uniform with most datapoints being from the USA, but there is a long tail of 40 other countries which are not well represented.\n",
    "\n",
    "Back in the __Performance & Fairness__ tab, we can set an input feature (or set of features) with which to slice the data. For example, setting this to `sex` allows us to see the breakdown of model performance on male datapoints versus female datapoints. We can see that the model is more accurate (has less false positives and false negatives) on females than males. We can also see that the model predicts high income for females much less than it does for males (8.0% of the time for females vs 27.1% of the time for males). __Note, your numbers will be slightly different due to the random elements of model training__.\n",
    "\n",
    "Imagine a scenario where this simple income classifier was used to approve or reject loan applications (not a realistic example but it illustrates the point). In this case, 28% of men from the test dataset have their loans approved but only 10% of women have theirs approved. If we wished to ensure than men and women get their loans approved the same percentage of the time, that is a fairness concept called \"demographic parity\". One way to achieve demographic parity would be to have different classification thresholds for males and females in our model.\n",
    "\n",
    "In this case, demographic parity can be found with both groups getting loans 16% of the time by having the male threshold at 0.67 and the female threshold at 0.31. Because of the vast difference in the properties of the male and female training data in this 1994 census dataset, we need quite different thresholds to achieve demographic parity. Notice how with the high male threshold there are many more false negatives than before, and with the low female threshold there are many more false positives than before. This is necessary to get the percentage of positive predictions to be equal between the two groups. WIT has buttons to optimize for other fairness constraints as well, such as \"equal opportunity\" and \"equal accuracy\". Note that the demographic parity numbers may be different from the ones in your text as the trained models are always a bit different.\n",
    "\n",
    "The use of these features can help shed light on subsets of your data on which your classifier is performing very differently. Understanding biases in your datasets and data slices on which your model has disparate performance are very important parts of analyzing a model for fairness. There are many approaches to improving fairness, including augmenting training data, building fairness-related loss functions into your model training procedure, and post-training inference adjustments like those seen in WIT. We think that WIT provides a great interface for furthering ML fairness learning, but of course there is no silver bullet to improving ML fairness."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training on a more balanced dataset\n",
    "\n",
    "Using the What-If Tool we saw that the model we trained on the census dataset wouldn't be very considerate in a production environment. What if we retrained the model on a dataset that was more balanced? Fortunately, we have such a dataset. Let's train a new model on this balanced dataset and compare it to our original dataset using the What-If Tool. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, let's load the balanced dataset into a Pandas dataframe."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bal_data_path = 'https://storage.googleapis.com/cloud-training/dei/balanced_census_data.csv' \n",
    "bal_data = pd.read_csv(bal_data_path, names=COLUMNS, skiprows=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bal_data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Execute the command below to see the distribution of gender in the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bal_data['sex'].value_counts(normalize=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Unlike the original dataset, this dataset has an equal number of rows for both males and females. Execute the command below to see the distriubtion of rows in the dataset of both `sex` and `income-level`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bal_data.groupby(['sex', 'income-level'])['sex'].count()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that not only is the dataset balanced across gender, it's also balanced across income. Let's train a model on this data. We'll use exactly the same model pipeline as in the previous section. Scikit-Learn has a convenient utility function for copying model pipelines, `clone`. The `clone` function copies a pipeline architecture without saving learned parameter values. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bal_data['income-level'] = bal_data['income-level'].isin(['>50K', '>50K.']).values.astype(int)\n",
    "\n",
    "raw_bal_features = bal_data.drop('income-level', axis=1).values\n",
    "bal_labels = bal_data['income-level'].values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipeline_bal = clone(pipeline)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipeline_bal.fit(raw_bal_features, bal_labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As before, we save our trained model to a pickle file. Note, when we version this model in AI Platform the model in this case must be named `model.pkl`. It's ok to overwrite the existing `model.pkl` file since we'll be uploading it to Cloud Storage anyway. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('model.pkl', 'wb') as model_file:\n",
    "    pickle.dump(pipeline_bal, model_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Deploy the model to AI Platform using the following bash script:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "\n",
    "gsutil cp model.pkl gs://$QWIKLABS_PROJECT_ID/balanced/\n",
    "    \n",
    "MODEL_NAME=\"census_income_classifier\"\n",
    "VERSION_NAME=\"balanced\"\n",
    "MODEL_DIR=\"gs://$QWIKLABS_PROJECT_ID/balanced/\"\n",
    "CUSTOM_CODE_PATH=\"gs://$QWIKLABS_PROJECT_ID/custom_transforms-0.1.tar.gz\"\n",
    "\n",
    "gcloud beta ai-platform versions create $VERSION_NAME \\\n",
    "  --model $MODEL_NAME \\\n",
    "  --runtime-version 1.15 \\\n",
    "  --python-version 3.7 \\\n",
    "  --origin $MODEL_DIR \\\n",
    "  --package-uris $CUSTOM_CODE_PATH \\\n",
    "  --prediction-class predictor.MyPredictor \\\n",
    "  --region=global"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's instantiate the What-if Tool by configuring a WitConfigBuilder. Here, we want to compare the original model we built with the one trained on the balanced census dataset. To achieve this we utilize the `set_compare_ai_platform_model` method. We want to compare the models on a balanced test set. The balanced test is loaded and then input to `WitConfigBuilder`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bal_test_csv_path = 'https://storage.googleapis.com/cloud-training/dei/balanced_census_data_test.csv'\n",
    "bal_test_data = pd.read_csv(bal_test_csv_path, names=COLUMNS, skipinitialspace=True)\n",
    "bal_test_data['income-level'] = (bal_test_data['income-level'] == '>50K').values.astype(int)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config_builder = (\n",
    "    WitConfigBuilder(bal_test_data.to_numpy()[1:].tolist(), COLUMNS)\n",
    "    .set_ai_platform_model(os.environ['QWIKLABS_PROJECT_ID'], 'census_income_classifier', 'original')\n",
    "    .set_compare_ai_platform_model(os.environ['QWIKLABS_PROJECT_ID'], 'census_income_classifier', 'balanced')\n",
    "    .set_target_feature('income-level')\n",
    "    .set_model_type('classification')\n",
    "    .set_label_vocab(['Under 50K', 'Over 50K'])\n",
    ")\n",
    "\n",
    "WitWidget(config_builder, height=800)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once the WIT widget loads, click on the __Performance & Fairness__ tab. In the __Slice by__ field select `sex` and wait a minute for the graphics to load. For females, the model trained on the balanced dataset is over two times more likely to predict an income of over 50k than the model trained on the original dataset. While this results in a higher false positive rate, the false negative rate is decreased by a factor of three. This results in an improved overall accuracy of some 10 percentage points. \n",
    "\n",
    "How else does the model trained on balanced data perform differently when compared to the original model? "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
